import {createContext} from 'react'
import {action, observable} from 'mobx'

class Modal {
  /**控制弹窗显示隐藏 */
  @observable visible: boolean = false
  /**弹窗标题 */
  @observable title: string = ''
  /**弹窗内容 */
  @observable content: ModalType.Content = ''
  /**弹窗确认按钮文本 */
  @observable confirmBtnText: string = '确认'
  /**弹窗取消按钮文本 */
  @observable cancelBtnText: string = '取消'
  /**弹窗确认事件回调 */
  @observable confirmCallback: ModalType.Callback | null = null
  /**弹窗取消事件回调 */
  @observable cancelCallback: (() => boolean) | null = null

  /**重置弹窗显示状态 */
  @action.bound
  resetVisible() {
    this.visible = false
  }
  /**重置弹窗按钮文本 */
  @action.bound
  resetBtnText() {
    this.confirmBtnText = '确认'
    this.cancelBtnText = '取消'
  }
  /**重置弹窗回调 */
  @action.bound
  resetCallback() {
    this.confirmCallback = null
    this.cancelCallback = null
  }
  /**重置弹窗内容 */
  @action.bound
  resetContent() {
    this.content = ''
  }
  /**重置弹窗标题 */
  @action.bound
  resetTitle() {
    this.title = ''
  }
  /**重置弹窗状态 */
  @action.bound
  resetModal() {
    this.resetBtnText()
    this.resetCallback()
    this.resetContent()
    this.resetModal()
    this.resetTitle()
    this.resetVisible()
  }
  /**弹窗确认事件 */
  @action.bound
  confirm() {
    if (this.confirmCallback && !this.confirmCallback()) return
    this.resetModal()
  }
  /**弹窗取消事件 */
  @action.bound
  cancel() {
    if (this.cancelCallback && this.cancelCallback() === false) return
    this.resetModal()
  }
  /**打开弹窗 */
  @action.bound
  openModal({
    title,
    content,
    confirm,
    cancel
  }: {
    title?: string
    content?: ModalType.Content
    confirm?: ModalType.Callback
    cancel?: ModalType.Callback
  }) {
    if (title) this.title = title
    if (content) this.content = content
    if (confirm) this.confirmCallback = confirm
    if (cancel) this.cancelCallback = cancel
    this.visible = true
  }
  /**关闭弹窗 */
  @action.bound
  closeModal() {
    this.resetModal()
  }
}

const modalStore = createContext(new Modal())
export default modalStore
